package common

import (
	"fmt"
	"gin/pkg"

	"github.com/jinzhu/gorm"
)

//查询人物关系的名称
func SelectOneRname(db *gorm.DB, Rno string) string {
	var Result pkg.RInfo
	err := db.Table("relation").Where("rno =?", Rno).Find(&Result).Error
	pkg.ErrCheck(err)
	return Result.Rname
}

//查询人物关系的名称
func SelectOneRno(db *gorm.DB, Rname string) string {
	var Result pkg.RInfo
	err := db.Table("relation").Where("rname =?", Rname).Find(&Result).Error
	pkg.ErrCheck(err)
	return Result.Rno
}

//查询单个家庭成员编号
func SelectOnePno(db *gorm.DB, name string) string {
	var Result pkg.PInfo
	err := db.Table("person").Where("pname =?", name).Find(&Result).Error
	pkg.ErrCheck(err)
	return Result.Pno
}

//查询单个家庭成员性别
func SelectOnePsex(db *gorm.DB, name string) string {
	var Result pkg.PInfo
	err := db.Table("person").Where("pname =?", name).Find(&Result).Error
	pkg.ErrCheck(err)
	return Result.Psex
}

//查询单个家庭成员信息
func SelectOnePerson(db *gorm.DB, name string) pkg.PInfo {
	var Result pkg.PInfo
	err := db.Table("person").Where("pname =?", name).Find(&Result).Error
	pkg.ErrCheck(err)
	return Result
}

//查询单个家庭成员关系信息
func SelectOnePR(db *gorm.DB, data pkg.PInfo) []pkg.PR_result {
	var Results []pkg.PR_result
	err := db.Table("person_relationship pr").
		Select("pr.pri_pname,pr.cor_pname,relation.rname").
		Joins("left  join relation on pr.cor_rno = relation.rno").
		Where("pr.pri_pname=? or pr.cor_pname =?", data.Pname, data.Pname).
		Find(&Results).Error
	pkg.ErrCheck(err)
	return Results
}

//查询家族信息
func SelectPerson(db *gorm.DB) {
	var Results []pkg.PInfo
	err := db.Table("person").Find(&Results).Error
	pkg.ErrCheck(err)
	for _, v := range Results {
		fmt.Println(v)
	}
}

//查询人物关系信息
func SelectRelation(db *gorm.DB) {
	var Results []pkg.RInfo
	err := db.Table("relation").Find(&Results).Error
	pkg.ErrCheck(err)
	for _, v := range Results {
		fmt.Println(v)
	}
}

//查询所有家庭成员关系
func SelectPRelation(db *gorm.DB) {
	var Results []pkg.PR_result
	err := db.Table("person_relationship pr").
		Select("pr.pri_pname,pr.cor_pname,relation.rname").
		Joins("left  join relation on pr.cor_rno = relation.rno").
		Find(&Results).Error
	pkg.ErrCheck(err)
	for _, v := range Results {
		fmt.Println(v)
	}
}

//查询人物基本信息
func SelectBaseInfo(db *gorm.DB, name string) pkg.PInfoBase {
	var Result pkg.PInfoBase
	err := db.Table("person").
		Select("pname,psex,pbtime,pdtime").
		Where("pname = ?", name).
		First(&Result).Error
	pkg.ErrCheck(err)
	return Result
}

//查询人物生平事迹
func SelectDeedInfo(db *gorm.DB, name string) pkg.PInfoDeed {
	var Result pkg.PInfoDeed
	err := db.Table("person").
		Select("pname,pbtime,pdtime,pintro,phonor").
		Where("pname = ?", name).
		First(&Result).Error
	pkg.ErrCheck(err)
	return Result
}
